import axios from 'axios';
import { Toast } from 'antd-mobile'

let baseUrl = ""
let $pre = ""
if (process.env.NODE_ENV === 'development') {
    $pre = 'http://localhost:1000'
    baseUrl = '/api';
}
export { $pre }
//请求拦截
axios.interceptors.request.use((config) => {
    config.url = baseUrl + config.url;
    if(config.url != baseUrl+'/api/login' && config.url != baseUrl+'/api/register'){
        let {token=''} = JSON.parse(sessionStorage.getItem('userInfo'));  
        config.headers.authorization = token;
    }
    return config;
})

//响应拦截
axios.interceptors.response.use((res,next) => {
    // console.log(res);
    if (res.data.code === 500) {    
        Toast.show({
            content: res.data.msg,
        });
    }
    if(res.data.msg === '登录已过期或访问权限受限'){
        Toast.show({
            content: res.data.msg,
        });
        sessionStorage.removeItem("userInfo")
        window.open("/", "_self")

    }
    return res;
})

export const get = (url, params={}) => {
    return axios({ url, method: 'get', params });
}

export const post = (url, params, flie = false) => {
    let data = null;
    if (flie) {
        let f = new FormData();
        for (let k in params) {
            f.append(k, params[k])
        }
        data = f;
    } else {
        data = params;
    }
    return axios({ url, method: 'post', data });
}